'use strict';

const Controller = require('egg').Controller;
const crypto = require("crypto");


class CommonController extends Controller {
  //银行卡 配置
  async view() {
    const { ctx, app } = this
    let list = await app.model.BankConfig.findAll()
    ctx.apiSuccess(list)
  }
  //扫描 赠送 推广二维码 查询数据
  async qrlist() {
    const { ctx, app } = this
    const { id, type } = ctx.request.body
    ctx.validate({
      id: {
        type: 'int',
        required: true,
        desc: 'id'
      },
      type: {
        type: 'string',
        required: true,
        range: {
          in: ['agent', 'collar']
        },
        desc: '类型'
      }
    })
    if (type == 'agent') { //推广

    } else { //赠送

    }
    ctx.apiSuccess('aa')
  }
  //商家登录
  async shoplogin() {
    const { ctx, app } = this;
    const { phone, pwd } = ctx.request.body
    ctx.validate({
      phone: {
        type: 'int',
        required: true,
        desc: '账号'
      },
      pwd: {
        type: "string",
        required: true,
        range: {
          max: 10,
          min: 2
        },
        desc: '密码'
      }
    })
    let userlist = await app.model.ShopUser.findOne({
      where: {
        phone,
        status: '1'
      }
    })
    if (!userlist) {
      ctx.throw(400, '账号不存在或者被禁用了')
    }
    //验证 密码
    const hmac = crypto.createHash("sha256", app.config.crypto.secret);
    hmac.update(pwd);
    let hash = hmac.digest("hex");
    if (userlist.pwd != hash) {
      ctx.throw(400, '密码错误')
    }
    let token = ctx.getToken(JSON.stringify({ id: userlist.id, shop_id: userlist.shop_id, nickname: userlist.nickname, phone: userlist.phone, role: userlist.role }))

    userlist.update({ token })
    ctx.apiSuccess(token)
  }
  //商家修改密码
  async reshoppwd() {
    const { ctx, app } = this;
    const { phone, pwd, repwd } = ctx.request.body;
    ctx.validate({
      phone: {
        type: 'int',
        required: true,
        desc: '账号'
      },
      pwd: {
        type: "string",
        required: true,
        range: {
          max: 10,
          min: 2
        },
        desc: '密码'
      },
      repwd: {
        type: "string",
        required: true,
        range: {
          max: 10,
          min: 2
        },
        desc: '新密码'
      }
    });
    let userlist = await app.model.ShopUser.findOne({
      where: {
        phone,
        status: '1'
      }
    });
    if (!userlist) {
      ctx.throw(400, '账号不存在或者被禁用了')
    };
    //验证 密码
    const hmac = crypto.createHash("sha256", app.config.crypto.secret);
    hmac.update(pwd);
    let hash = hmac.digest("hex");
    if (userlist.pwd != hash) {
      ctx.throw(400, '密码错误')
    }
    let updatalist = await userlist.update({ pwd: repwd })
    if (!updatalist) {
      ctx.apiFail('修改失败')
    } else {
     ctx.apiSuccess('修改成功')
    }
  }
}

module.exports = CommonController;
